﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;
using DataAccessObject;
using EntityObject;
using SharedLibraries;
using SharedLibraries.Constants;
using ThangNM_LIB.FUNC;

namespace ThangNM.UserControl.Admin
{
    public partial class WeddingUC : System.Web.UI.UserControl
    {
        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            Title_FormUC1.setTitle(ConstEx.Table_Name_C.Wedding, ConstEx.funcButtonToolBar.LIST);
            MsgUC1.setClearMsg();
            //if ((new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), ConstEx.funcButtonToolBar.MAIN) == false)
            //{
            //    Commons.setAccessDenied(Page, MsgUC1);
            //    return;
            //}
            if (!IsPostBack)
            {
                ToolBarUC1.ViewGroupButtonByFunction(ConstEx.funcButtonToolBar.LIST);
                ToolBarUC1.BindData_DropDownList(GetListConstants.Wedding_iGroom_GLC());
                ToolBarUC1.SetDefaultValue(0);
                BindData_DropDownList();
                BindData_List(null);
                BindData_Detail(new WeddingEO() { tPartySC = new DateTime(2015, 10, 01, 16, 00, 00), tPartyLC = new DateTime(2015, 08, 19, 16, 00, 00) });
                SetViewToolBar(true);
            }
            ToolBarUC1.btnExportExcel.Text = "[Alt+U] Cập nhật";
            ToolBarUC1.btnExportExcel.AccessKey = "U";
            ToolBarUC1.btnExportExcel.OnClientClick = "return confirm('Bạn có muốn sửa bản ghi này không?');";
            ToolBarUC1.btnRefreshList.Text = "Quay lại thêm mới";
        }

        protected void BindData_DropDownList()
        {
            ddliGroom.DataSource = GetListConstants.Wedding_iGroom_GLC();
            ddliGroom.DataValueField = "Key";
            ddliGroom.DataTextField = "Value";
            ddliGroom.DataBind();

            ddliStatus.DataSource = GetListConstants.Wedding_iStatus_GLC();
            ddliStatus.DataValueField = "Key";
            ddliStatus.DataTextField = "Value";
            ddliStatus.DataBind();
        }
        public void BindData_List(String sSortColumn)
        {
            try
            {
                List<WeddingEO> lst = new List<WeddingEO>();
                grvList.Visible = false;
                string keysearch = StringEx.Trim(SearchUI1.txtTextSearch.Text).ToUpper();
                DataTable dt = (new WeddingDAO()).SelectBy_iGroom(Convert.ToInt16(ToolBarUC1.ddlStatus.SelectedValue));
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[PK_gWeddingID] DESC";
                dt = dv.ToTable();
                var result = (List<WeddingEO>)ConvertEx.ConvertDataTableToListObject<WeddingEO>(dt, lst.GetType());
                if (result != null)
                {
                    if (SearchUI1.ddlTypeSearch.SelectedValue.Equals("0"))
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.sName.ToString(), keysearch));
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(keysearch))
                        {
                            result = result.FindAll(x => StringEx.CompareEx(x.sNameEx, keysearch));
                        }
                    }
                    if (result.Count() > 0)
                    {
                        grvList.Visible = true;
                        grvList.DataSource = result.ToList();
                        grvList.DataBind();
                        lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + result.Count();
                        return;
                    }
                }
                grvList.DataSource = null;
                grvList.DataBind();
                lblRowCount.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        public void BindData_Detail(WeddingEO _WeddingEO)
        {
            txtPK_gWeddingID.Text = _WeddingEO.PK_gWeddingID.ToString();
            txtsName.Text = _WeddingEO.sName;
            txtsNameEx.Text = _WeddingEO.sNameEx;
            txtsRelationship.Text = _WeddingEO.sRelationship;
            txtsNote.Text = _WeddingEO.sNote;
            txtsEmail.Text = _WeddingEO.sEmail;
            txttPartySC.Text = _WeddingEO.tPartySC.ToString(FormatEx.Date_Time.Format_DateTime_Local_Html5);
            txttPartyLC.Text = _WeddingEO.tPartyLC.ToString(FormatEx.Date_Time.Format_DateTime_Local_Html5);
            ddliGroom.SelectedValue = _WeddingEO.iGroom.ToString();
            ddliStatus.SelectedValue = _WeddingEO.iStatus.ToString();
            hplsUrl.Text = _WeddingEO.PK_gWeddingID.ToString();
            hplsUrl.NavigateUrl = "http://nguyenmanhthang.net/nguyenhoaiduong?td=" + txtPK_gWeddingID.Text;
        }

        #region "Event Handler"
        protected void Search_Click(object sender, EventArgs e)
        {
            BindData_List(null);
        }

        protected void EventButtonToolBar_Click(object sender, CustomerEventArgs e)
        {
            //if ((new ShareDAO.UserDAO()).SelectBy_sPermission(Session["secret"], Convert.ToString(Request.Url.AbsolutePath), e.iType) == false)
            //{
            //    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.DANGER, MessagesEx.Khong_Co_Quyen_Truy_Cap, null);
            //    Commons.setAccessDenied(Page, null);
            //    return;
            //}
            switch (e.iType)
            {
                case ConstEx.funcButtonToolBar.INSERT_LIST:
                    InsertItem();
                    //if (Insert != null)
                    //    Insert(this, EventArgs.Empty);
                    break;
                case ConstEx.funcButtonToolBar.INSERT_ITEM: break;
                case ConstEx.funcButtonToolBar.UPDATE_ITEM:
                    UpdateItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_LIST:
                    DeleteItem();
                    break;
                case ConstEx.funcButtonToolBar.DELETE_ITEM: break;
                case ConstEx.funcButtonToolBar.REFRESH_LIST:
                    //ResetFormSearch();
                    BindData_List(null);
                    SetViewToolBar(true);
                    break;
                case ConstEx.funcButtonToolBar.EXPORT_EXCEL:
                    UpdateItem();
                    //if (grvList.PageCount > 0)
                    //{
                    //    Export_Lib.PDF_Export(grvList, "Wedding");
                    //}
                    //else
                    //{
                    //    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Không thể xuất file vì không có bản ghi nào.", null);
                    //}
                    break;
                case ConstEx.funcButtonToolBar.RESET_FORM: break;
            }
        }

        protected void EventSelectChange_Click(object sender, CustomerEventArgs e)
        {
            if (e != null)
            {
                BindData_List(null);
            }
        }
        #endregion

        #region "Event GridView"
        protected void grvList_RowCommand(object source, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "cmdView")
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument) % grvList.PageSize;
                Guid PK_gWeddingID = new Guid(Convert.ToString(grvList.DataKeys[rowIndex].Values[0]));
                WeddingEO _WeddingEO = new WeddingEO();
                _WeddingEO = (new WeddingDAO()).SelectItem(PK_gWeddingID);
                BindData_Detail(_WeddingEO);
                SetViewToolBar(false);
                //if (ViewDetail != null)
                //    ViewDetail(this, new CustomerEventArgs(1, "Oki", _WeddingEO));
            }
        }

        protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvList.PageIndex = e.NewPageIndex;
            BindData_List(null);
        }

        protected void grvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_List("[" + e.SortExpression + "]" + " DESC");
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_List("[" + e.SortExpression + "]" + " ASC");
            }
        }
        #endregion

        protected bool CheckInput()
        {
            string strNull = "";
            if (string.IsNullOrEmpty(txtPK_gWeddingID.Text) == true)
            {
                strNull += ", " + lblPK_gWeddingID.Text;
                txtPK_gWeddingID.Focus();
            }
            if (string.IsNullOrEmpty(txtsName.Text) == true)
            {
                strNull += ", " + lblsName.Text;
                txtsName.Focus();
            }
            //if (string.IsNullOrEmpty(txtsRelationship.Text) == true)
            //{
            //    strNull += ", " + lblsRelationship.Text;
            //    txtsRelationship.Focus();
            //}
            if (string.IsNullOrEmpty(txttPartySC.Text) == true)
            {
                strNull += ", " + lbltPartySC.Text;
                txttPartySC.Focus();
            }
            if (string.IsNullOrEmpty(txttPartyLC.Text) == true)
            {
                strNull += ", " + lbltPartyLC.Text;
                txttPartyLC.Focus();
            }
            if ((string.IsNullOrEmpty(ddliGroom.SelectedValue) == true) || (ddliGroom.SelectedValue.Equals("0")))
            {
                strNull += ", " + lbliGroom.Text;
                ddliGroom.Focus();
            }
            if ((string.IsNullOrEmpty(ddliStatus.SelectedValue) == true) || (ddliStatus.SelectedValue.Equals("0")))
            {
                strNull += ", " + lbliStatus.Text;
                ddliStatus.Focus();
            }
            if (String.IsNullOrEmpty(strNull))
            {
                if (Convert.ToDateTime(txttPartySC.Text) < (new DateTime(2015, 09, 30, 00, 00, 00)))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Ngày dương lịch phải nhập trong khoảng 30/09/2015 00:00 đến 01/10/2015 23:59", null);
                    return false;
                }
                else if (Convert.ToDateTime(txttPartySC.Text) > (new DateTime(2015, 10, 01, 23, 59, 59)))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Ngày dương lịch phải nhập trong khoảng 30/09/2015 00:00 đến 01/10/2015 23:59", null);
                    return false;
                }
                if (Convert.ToDateTime(txttPartyLC.Text) < (new DateTime(2015, 08, 18, 00, 00, 00)))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Ngày âm lịch phải nhập trong khoảng 18/08/2015 00:00 đến 19/08/2015 23:59", null);
                    return false;
                }
                else if (Convert.ToDateTime(txttPartyLC.Text) > (new DateTime(2015, 08, 19, 23, 59, 59)))
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, "Ngày âm lịch phải nhập trong khoảng 18/08/2015 00:00 đến 19/08/2015 23:59", null);
                    return false;
                }
                return true;
            }
            else
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, MessagesEx.CAC_TRUONG_BAT_BUOC_PHAI_NHAP + strNull.Substring(2).Replace(":", ""), null);
                return false;
            }
        }

        protected void GetObject(ref WeddingEO _WeddingEO)
        {
            try
            {
                _WeddingEO.PK_gWeddingID = new Guid(txtPK_gWeddingID.Text);
                _WeddingEO.sName = txtsName.Text;
                _WeddingEO.sNameEx = txtsNameEx.Text;
                _WeddingEO.sRelationship = txtsRelationship.Text;
                _WeddingEO.sNote = txtsNote.Text;
                _WeddingEO.sEmail = txtsEmail.Text;
                _WeddingEO.tPartySC = Convert.ToDateTime(txttPartySC.Text);
                _WeddingEO.tPartyLC = Convert.ToDateTime(txttPartyLC.Text);
                _WeddingEO.iGroom = Convert.ToInt16(ddliGroom.SelectedValue);
                _WeddingEO.iStatus = Convert.ToInt16(ddliStatus.SelectedValue);
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        public void InsertItem()
        {
            try
            {
                if (CheckInput())
                {
                    WeddingEO _WeddingEO = new WeddingEO();
                    GetObject(ref _WeddingEO);
                    if (_WeddingEO == null)
                        return;
                    _WeddingEO.PK_gWeddingID = Guid.NewGuid();
                    if ((new WeddingDAO()).Insert_Update_Delete(_WeddingEO, 1) == true)
                    {
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Them_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                        BindData_List(null);
                        BindData_Detail(new WeddingEO() { PK_gWeddingID = Guid.NewGuid(), tPartySC = new DateTime(2015, 10, 01, 16, 00, 00), tPartyLC = new DateTime(2015, 08, 19, 16, 00, 00) });
                    }
                    else
                    {
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Them_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                    }
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        public void UpdateItem()
        {
            try
            {
                if (CheckInput())
                {
                    WeddingEO _WeddingEO = new WeddingEO();
                    GetObject(ref _WeddingEO);
                    if (_WeddingEO == null)
                        return;
                    if ((new WeddingDAO()).Insert_Update_Delete(_WeddingEO, 2) == true)
                    {
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Sua_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                        BindData_List(null);
                        BindData_Detail(new WeddingEO() { PK_gWeddingID = Guid.NewGuid(), tPartySC = new DateTime(2015, 10, 01, 16, 00, 00), tPartyLC = new DateTime(2015, 08, 19, 16, 00, 00) });
                        SetViewToolBar(true);
                    }
                    else
                    {
                        MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Sua_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                    }
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        public void DeleteItem()
        {
            try
            {
                WeddingEO _WeddingEO = new WeddingEO();
                GetObject(ref _WeddingEO);
                if (_WeddingEO == null)
                    return;
                if ((new WeddingDAO()).Insert_Update_Delete(_WeddingEO, 3) == true)
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.SUCCESS, String.Format(MessagesEx.Xoa_Thanh_Cong_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                    BindData_List(null);
                    BindData_Detail(new WeddingEO() { PK_gWeddingID = Guid.NewGuid(), tPartySC = new DateTime(2015, 10, 01, 16, 00, 00), tPartyLC = new DateTime(2015, 08, 19, 16, 00, 00) });
                    SetViewToolBar(true);
                }
                else
                {
                    MsgUC1.setNotifications(ConstEx.FunctionSetMsg.WARNING, String.Format(MessagesEx.Xoa_That_Bai_Ma_Ten, ConstEx.Table_Name_C.Wedding, _WeddingEO.PK_gWeddingID, _WeddingEO.sName), null);
                }
            }
            catch (Exception ex)
            {
                MsgUC1.setNotifications(ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        public void SetViewToolBar(Boolean isInsert)
        {
            ToolBarUC1.btnInsert.Visible = isInsert;
            ToolBarUC1.btnRefreshList.Visible = (!isInsert);
            ToolBarUC1.btnDeleteList.Visible = (!isInsert);
            ToolBarUC1.btnExportExcel.Visible = (!isInsert);
        }

        protected void grvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lbliStatus = (Label)e.Row.FindControl("lbliStatus");
                lbliStatus.Text = GetListConstants.getValueKeyInSortedList(GetListConstants.Wedding_iStatus_GLC(), Convert.ToInt16(lbliStatus.Text), false); ;
            }
        }
    }
}